package LC;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * https://leetcode.com/problems/fraction-to-recurring-decimal/description/
 * Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
 * If the fractional part is repeating, enclose the repeating part in parentheses.
 * For example,
 * Given numerator = 1, denominator = 2, return "0.5".
 * Given numerator = 2, denominator = 1, return "2".
 * Given numerator = 2, denominator = 3, return "0.(6)".
 * Credits:
 * Special thanks to @Shangrila for adding this problem and creating all test cases.
 */
public class LC_166_FractiontoRecurringDecimal_String {
    public static void main(String[] args) {
        System.out.println(Solution.fractionToDecimal(2, 3));
    }

    static class Solution {
        static String fractionToDecimal(int numerator, int denominator) {
            HashMap<Long, Integer> maps = new HashMap<>();
            List<Long> number = new ArrayList<>();
            int index = 0;
            int beginIndex = -1;
            StringBuilder builder = new StringBuilder();
            if (denominator == 0) return "";
            long num = numerator;
            long denum = denominator;
            if ((num < 0 && denum > 0) || (num > 0 && denum < 0)) builder.append('-');
            num = Math.abs(num);
            denum = Math.abs(denum);
            long val = num / denum;
            builder.append(String.valueOf(val));
            num = (num % denum) * 10;
            while (num != 0) {
                if (maps.containsKey(num)) {
                    beginIndex = maps.get(num);
                    break;
                } else {
                    maps.put(num, index++);
                    val = num / denum;
                    num = (num % denum) * 10;
                    number.add(val);
                }
            }
            for (int i = 0; i < index; i++) {
                if (i == 0)
                    builder.append('.');
                if (i == beginIndex)
                    builder.append('(');
                builder.append(number.get(i));
            }
            if (beginIndex != -1)
                builder.append(')');
            return builder.toString();
        }
    }
}